package net.xiaoboli.mgp;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.logging.Log;
import org.mybatis.generator.logging.LogFactory;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;

public class BaseMapperPlugin extends PluginAdapter {
    private Log log;

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        this.log = LogFactory.getLog(this.getClass());
    }

    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        // 获取原始文件名
        String originalName = introspectedTable.getMyBatis3XmlMapperFileName();
        String prefix = originalName.substring(0, originalName.length() - "Mapper.xml".length());

        //
        String newName = prefix + properties.getProperty("suffix", "0Mapper") + ".xml";
        introspectedTable.setMyBatis3XmlMapperFileName(newName);

        // 删除原有文件
        String[] deletes = properties.getProperty("deletes", "Mapper").split(",");
        for (String item : deletes) {
            if (StringUtils.isNotBlank(item)) {
                String targetProject = getContext().getSqlMapGeneratorConfiguration().getTargetProject();
                String targetPackage = getContext().getSqlMapGeneratorConfiguration().getTargetPackage();
                File oldFile = Paths.get(targetProject, targetPackage.replace(".", "/"), prefix + item + ".xml").toFile();
                if (oldFile.exists()) {
                    log.warn("Delete mapper file: " + oldFile.getPath());
                    oldFile.delete();
                }
            }
        }

        //
        return true;
    }

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }
}

